<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import SourceSelectDialog from '@/views/warehouseoperations/SourceSelectDialog.vue'
import TargetSelectDialog from '@/views/warehouseoperations/TargetSelectDialog.vue'
import LocationSelectDialog from '@/views/warehouseoperations/LocationSelectDialog.vue'
import { addOperationApi } from '@/api/operation/operations'
import { batchAddDetailsApi, getByIdApi } from '@/api/operation/operationsdetails'

// 弹窗状态
const dialogVisible = ref(false)
const dialogTitle = ref('')

// 操作类型 (1: 组合加工, 2: 拆分加工)
const operationType = ref(null)

// 作业ID
const operationId = ref(null)

// 来源和目标数据
const sourceData = ref([])
const targetData = ref([])

// 弹窗引用
const sourceSelectDialogRef = ref(null)
const targetSelectDialogRef = ref(null)
const locationSelectDialogRef = ref(null)

// 打开弹窗
const open = (type, id = null) => {
  operationType.value = type
  operationId.value = id

  // 设置标题
  dialogTitle.value = type === 1 ? '组合加工' : '拆分加工'

  dialogVisible.value = true

  // 如果有ID，获取现有数据
  if (id) {
    fetchOperationData(id)
  } else {
    // 新增时清空数据
    sourceData.value = []
    targetData.value = []
  }
}

// 关闭弹窗
const closeDialog = () => {
  dialogVisible.value = false
  operationType.value = null
  operationId.value = null
}


// 处理来源确认
const handleSourceConfirm = (items) => {
  if (isSplitOperation.value) {
    // 拆分操作：来源只能有一个商品
    sourceData.value = items.length > 0 ? [items[items.length - 1]] : []
  } else {
    // 组合操作：来源可以有多个商品
    sourceData.value = items
  }
}
// 是否为拆分操作
const isSplitOperation = computed(() => operationType.value === 2)

// 提交数据
const submitData = async () => {
  try {
    // 验证数据
    if (sourceData.value.length === 0) {
      ElMessage.warning('请至少选择一个来源商品')
      return
    }

    if (targetData.value.length === 0) {
      ElMessage.warning('请至少选择一个目标商品')
      return
    }

    // 拆分操作验证：来源只能有一个商品
    if (isSplitOperation.value && sourceData.value.length > 1) {
      ElMessage.warning('拆分操作只能选择一个来源商品')
      return
    }

    // 组合操作验证：目标只能有一个商品
    if (!isSplitOperation.value && targetData.value.length > 1) {
      ElMessage.warning('组合操作只能选择一个目标商品')
      return
    }

    // 验证目标商品是否都选择了仓库
    const missingWarehouse = targetData.value.some(item => !item.warehouseinfo)
    if (missingWarehouse) {
      ElMessage.warning('请为目标商品选择仓库')
      return
    }

    // 创建作业主表数据
    const operationData = {
      category: operationType.value, // 1: 组合加工, 2: 拆分加工
      status: 1,  // 1未确认
      empId: 1,   // 实际应根据登录用户确定
    }

    // 添加作业主表记录
    const operationRes = await addOperationApi(operationData)

    // 安全地获取作业ID
    let newOperationId = null
    if (operationRes && operationRes.data) {
      newOperationId = operationRes
    } else if (operationRes) {
      newOperationId = operationRes
    }

    // 检查是否成功获取到作业ID
    if (!newOperationId) {
      throw new Error('无法获取作业ID: ' + JSON.stringify(operationRes))
    }

    // 构造来源商品数据
    const sourceItems = sourceData.value.map(item => ({
      skuId: item.skuId || item.id || 0,     // 商品ID
      sourceCount: item.count || 1,          // 使用数量
      targetCount: 0,                        // 来源商品没有目标数量
      price: 0,                              // 来源商品没有价格
      warehouseOperationsId: newOperationId,  // 作业ID
      targetWarehouseId: 0,                  // 来源商品没有目标仓库
      targetWarehouseAreaId: 0,              // 来源商品没有目标库区
      targetWarehouseAreaLocaId: 0,          // 来源商品没有目标库位
      category: 1,                           // 类型: 1 来源
    }))

    // 构造目标商品数据（包含仓库信息）
    const targetItems = targetData.value.map(item => {
      // 从行数据中获取仓库信息
      const warehouseInfo = item.warehouseinfo || {}

      return {
        skuId: item.skuId || item.id || 0,     // 商品ID
        sourceCount: 0,                        // 目标商品没有来源数量
        targetCount: item.count || 1,          // 加工产出数量
        price: item.price || 0,                // 商品价格
        warehouseOperationsId: newOperationId,  // 作业ID
        targetWarehouseId: warehouseInfo.id || warehouseInfo.warehouseId || 0,        // 目标仓库ID
        targetWarehouseAreaId: warehouseInfo.warehouseAreaId || warehouseInfo.areaId || 0, // 目标库区ID
        targetWarehouseAreaLocaId: warehouseInfo.warehouseAreaLocaId || warehouseInfo.locationId || 0,  // 目标库位ID
        category: 2,                           // 类型: 2 目标
      }
    })

    // 合并来源和目标数据
    const allDetails = [...sourceItems, ...targetItems]

    // 批量添加作业详情
    await batchAddDetailsApi(allDetails)

    ElMessage.success('操作成功')
    closeDialog()
  } catch (error) {
    console.error('提交数据失败:', error)
    ElMessage.error('操作失败: ' + (error.message || error.toString() || '未知错误'))
  }
}

// 获取作业数据
const fetchOperationData = async (id) => {
  try {
    const res = await getByIdApi(id)
    if (res.code) {
      // 从返回的数据中区分来源和目标数据
      const allItems = res.data || []

      // 根据category区分来源和目标数据
      const sourceItems = allItems.filter(item => item.category === 1)
      const targetItems = allItems.filter(item => item.category === 2)

      // 根据操作类型处理数据
      if (isSplitOperation.value) {
        // 拆分操作：来源只能有一个商品，目标可以有多个
        sourceData.value = sourceItems.slice(0, 1) // 只取第一个作为来源
        targetData.value = targetItems // 目标可以有多个
      } else {
        // 组合操作：来源可以有多个商品，目标只能有一个
        sourceData.value = sourceItems // 来源可以有多个
        targetData.value = targetItems.slice(0, 1) // 只取第一个作为目标
      }

      // 为目标商品添加仓库信息（如果需要显示）
      targetData.value = targetData.value.map(item => {
        // 如果已经有warehouseinfo则不重复添加
        if (item.warehouseinfo) {
          return item
        }

        // 根据目标商品的仓库ID信息构造warehouseinfo对象
        return {
          ...item,
          count: item.targetCount, // 显示目标数量
          price: item.price,
          warehouseinfo: {
            id: item.targetWarehouseId,
            warehouseId: item.targetWarehouseId,
            warehouseAreaId: item.targetWarehouseAreaId,
            locaId: item.targetWarehouseAreaLocaId
          }
        }
      })

      // 为来源商品处理显示数据
      sourceData.value = sourceData.value.map(item => {
        return {
          ...item,
          count: item.sourceCount // 显示来源数量
        }
      })
    }
  } catch (error) {
    console.error('获取作业数据失败:', error)
  }
}

// 打开来源选择弹窗
const openSourceSelectDialog = () => {
  if (sourceSelectDialogRef.value) {
    sourceSelectDialogRef.value.open('source', operationType.value)
  }
}

// 打开目标选择弹窗
const openTargetSelectDialog = () => {
  if (targetSelectDialogRef.value) {
    targetSelectDialogRef.value.open('target')
  }
}


// 处理目标确认
const handleTargetConfirm = (items) => {
  if (isSplitOperation.value) {
    // 拆分操作：目标可以有多个商品
    // 合并新选择的商品到现有目标数据中，避免重复
    const newItems = [...targetData.value]
    items.forEach(item => {
      // 检查是否已存在相同ID的商品
      const exists = newItems.some(existingItem => existingItem.id === item.id)
      if (!exists) {
        // 添加默认数量和价格属性
        newItems.push({
          ...item,
          count: 1, // 默认数量为1
          price: item.price || 0 // 默认价格为0
        })
      }
    })
    targetData.value = newItems
  } else {
    // 组合操作：目标只能有一个商品
    targetData.value = items.length > 0 ? [items[items.length - 1]] : []
  }
}

// 删除项目
const removeItem = (item, type) => {
  if (type === 'source') {
    sourceData.value = sourceData.value.filter(i => i.id !== item.id)
  } else {
    targetData.value = targetData.value.filter(i => i.id !== item.id)
  }
}

// 当前正在编辑的目标行
const currentEditingRow = ref(null)

// 打开库位选择弹窗
const openLocationSelectDialog = (row) => {
  // 保存当前正在编辑的行
  currentEditingRow.value = row
  if (locationSelectDialogRef.value) {
    locationSelectDialogRef.value.open('target')
  }
}

// 处理库位确认
const handleLocationConfirm = (items) => {
  // 检查是否有选中的库位和正在编辑的行
  if (items.length > 0 && currentEditingRow.value) {
    // 将选中的仓库信息存储到当前行的warehouseinfo属性中
    const selectedLocation = items[0] // 只取第一个选中的库位

    // 将完整的库位信息存储到行数据中
    currentEditingRow.value.warehouseinfo = selectedLocation

    // 更新目标数据以触发视图更新
    targetData.value = [...targetData.value]
  }

  // 清空当前编辑行
  currentEditingRow.value = null
}

// 暴露方法
defineExpose({
  open,
  closeDialog
})
</script>

<template>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="90%" :close-on-click-modal="false">
    <SourceSelectDialog ref="sourceSelectDialogRef" @confirm="handleSourceConfirm" />
    <TargetSelectDialog ref="targetSelectDialogRef" @confirm="handleTargetConfirm" />
    <LocationSelectDialog ref="locationSelectDialogRef" @confirm="handleLocationConfirm" />

    <!-- 来源和目标区域 -->
    <div class="source-target-container">
      <div class="source-section">
        <div class="section-header">
          <span>来源</span>
          <el-button type="primary" size="small" @click="openSourceSelectDialog">+</el-button>
        </div>
        <el-table :data="sourceData" style="width: 100%" border>
          <el-table-column type="selection" width="55" />
          <el-table-column prop="warehouseName" label="仓库名称" width="120" />
          <el-table-column prop="warehouseAreaLocaLocaCode" label="库位编码" width="120" />
          <el-table-column prop="skuCode" label="商品编码" width="120" />
          <el-table-column prop="skuTitle" label="商品名称" width="120" />
          <el-table-column prop="count" label="可用数量" width="120" />
          <el-table-column prop="createTime" label="入库时间" width="120" />
          <el-table-column label="操作" width="80">
            <template #default="{ row }">
              <el-button size="small" type="danger" @click="removeItem(row, 'source')">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="target-section">
        <div class="section-header">
          <span>目标</span>
          <el-button type="primary" size="small" @click="openTargetSelectDialog">+</el-button>
        </div>
        <el-table :data="targetData" style="width: 100%" border>
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="商品id" width="120" />
          <el-table-column prop="code" label="商品编码" width="120" />
          <el-table-column prop="subtitle" label="商品名称" width="120" />
          <el-table-column prop="count" label="数量" width="120">
            <template #default="{ row }">
              <el-input-number v-model="row.count" :min="1" size="small" />
            </template>
          </el-table-column>
          <el-table-column prop="price" label="商品价格" width="120">
            <template #default="{ row }">
              <el-input-number v-model="row.price" :min="0" size="small" />
            </template>
          </el-table-column>
          <el-table-column prop="targetWarehouse" label="目标仓库" width="90">
            <template #default="{ row }">
              <el-button type="success" @click="openLocationSelectDialog(row)">+</el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="{ row }">
              <el-button size="small" type="danger" @click="removeItem(row, 'target')">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 底部按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">关闭</el-button>
        <el-button type="primary" @click="submitData">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.operation-dialog-content {
  height: 70vh;
  overflow-y: auto;
}

.source-target-container {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  height: 400px;
  overflow-y: auto;
}

.source-section,
.target-section {
  flex: 1;
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 10px;
  height: 100%;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 表格样式调整 */
.el-table {
  flex: 1;
  overflow-y: auto;
}
</style>